package com.netdisk.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.netdisk.entity.File;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 文件Mapper接口
 */
@Mapper
public interface FileMapper extends BaseMapper<File> {

    /**
     * 根据用户ID和文件类型统计文件数量
     *
     * @param userId 用户ID
     * @param type 文件类型
     * @return 文件数量
     */
    @Select("SELECT COUNT(*) FROM files WHERE user_id = #{userId} AND (type = #{type} OR type LIKE CONCAT(#{type}, '/%')) AND deleted_at IS NULL")
    int countByUserIdAndType(@Param("userId") Integer userId, @Param("type") String type);
    
    /**
     * 分页查询用户文件列表
     *
     * @param page 分页参数
     * @param userId 用户ID
     * @return 分页结果
     */
    @Select("SELECT * FROM files WHERE user_id = #{userId} AND deleted_at IS NULL ORDER BY created_at DESC")
    IPage<File> selectPageByUserId(Page<File> page, @Param("userId") Integer userId);

    /**
     * 直接使用SQL查询用户文件列表，显式排除已删除的文件
     * 
     * @param offset 分页参数
     * @param userId 用户ID
     * @return 分页结果
     */
    @Select("SELECT * FROM files WHERE user_id = #{userId} AND deleted_at IS NULL ORDER BY created_at DESC LIMIT #{limit} OFFSET #{offset}")
    List<File> selectUserFilesDirectSQL(@Param("userId") Integer userId, @Param("limit") Integer limit, @Param("offset") Integer offset);

    /**
     * 直接使用SQL统计用户未删除文件数量
     * 
     * @param userId 用户ID
     * @return 文件数量
     */
    @Select("SELECT COUNT(*) FROM files WHERE user_id = #{userId} AND deleted_at IS NULL")
    int countUserNonDeletedFiles(@Param("userId") Integer userId);

    @Select("SELECT * FROM files WHERE user_id = #{userId} AND deleted_at IS NULL AND name LIKE CONCAT('%', #{query}, '%') ORDER BY created_at DESC LIMIT #{limit} OFFSET #{offset}")
    List<File> selectUserFilesWithQuery(@Param("userId") Integer userId, @Param("limit") Integer limit, @Param("offset") Integer offset, @Param("query") String query);


    @Select("SELECT COUNT(*) FROM files WHERE user_id = #{userId} AND deleted_at IS NULL AND name LIKE CONCAT('%', #{query}, '%')")
    int countUserNonDeletedFilesWithQuery(@Param("userId") Integer userId, @Param("query") String query);

}